package com.zyk.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zhangsan
 * @date 2021/4/25 21:39
 */
public class C15 {

    List<List<Integer>> ans;
    List<Integer> help;

    public List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 3) return new ArrayList<>();
        Arrays.sort(nums);
        ans = new ArrayList<>();
        twoSum(nums, 0, nums.length - 1, -nums[0]);
        for (int i = 1; i < nums.length - 2; i++) {
            if (nums[i] == nums[i - 1]) continue;
            if (-nums[i] < 0) break; // 因为排好序了, 所以此时小于0了, 就直接跳出循环
            twoSum(nums, i, nums.length - 1, -nums[i]);
        }
        return ans;
    }

    // nums有序, 从l ~ r 找到和为target的值, 将它们塞到ans中
    public void twoSum(int[] nums, int start, int r, int target) {
        int l = start + 1;
        while (l < r) {
            int v = nums[l] + nums[r];
            if (v == target) {
                help = new ArrayList<>();
                help.add(nums[start]);
                help.add(nums[l]);
                help.add(nums[r]);
                ans.add(help);
                l++;
                while (l < nums.length && nums[l] == nums[l - 1]) l++;
            } else if (v < target) {
                l++;
                while (l < nums.length && nums[l] == nums[l - 1]) l++;
            } else {
                r--;
                while (r >= 0 && nums[r] == nums[r + 1]) r--;
            }
        }
    }


    // for test
    public static void main(String[] args) {
        C15 test = new C15();
        int[] nums = {-2, 0, 1, 1, 2};
        System.out.println(test.threeSum(nums));
    }

}
